package com.example.testing.ipcdemo;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.util.Log;

/**
 * Created by tangjiangxu on 9/6/17.
 */

public class MessengerService extends Service {
    private static final String TAG = "MessengerService";

    public static final int MSG_FROM_CLIENT = 10000;
    public static final int MSG_FROM_SERVICE = 10001;


    private static class MessengerHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_FROM_CLIENT:
                    //msg.getData得到的是一个Bundle对象
                    Log.e(TAG, "handleMessage: msg:" + msg.getData().getString("msg"));
                    Messenger mMessenger = msg.replyTo;
                    if (mMessenger != null) {
                        Message serverMsg = Message.obtain(null, MSG_FROM_SERVICE);
                        Bundle bundle = new Bundle();
                        bundle.putString("reply", "this is server");
                        serverMsg.setData(bundle);
                        try {
                            mMessenger.send(serverMsg);
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                    }

                    break;
                default:
                    break;
            }
        }
    }

    private final Messenger mMessenger = new Messenger(new MessengerHandler());

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mMessenger.getBinder();
    }
}
